import { utils } from 'xlsx';
import * as XLSXStyle from 'xlsx-style-vite';
import FileSaver from 'file-saver';

export default function exportExcel(selector, sheetName, titleNum, fileName = 'excel.xlsx') {
  sheetName = sheetName || 'Sheet1';
  titleNum = titleNum || 3;
  /* generate workbook object from table */
  const wb = utils.book_new();
  const sheet = utils.table_to_sheet(document.querySelector(selector), { raw: true });
  utils.book_append_sheet(wb, sheet, sheetName);
  const range = utils.decode_range(wb.Sheets[sheetName]['!ref']);
  //单元格边框样式
  const borderStyle = {
    top: {
      style: 'thin',
      color: { rgb: '000000' }
    },
    bottom: {
      style: 'thin',
      color: { rgb: '000000' }
    },
    left: {
      style: 'thin',
      color: { rgb: '000000' }
    },
    right: {
      style: 'thin',
      color: { rgb: '000000' }
    }
  };
  const cWidth = [];
  for (let C = range.s.c; C <= range.e.c; C++) {
    //SHEET列
    let len = 100; //默认列宽
    const len_max = 400; //最大列宽
    for (let R = range.s.r; R <= range.e.r; R++) {
      //SHEET行
      const cell = { c: C, r: R }; //二维 列行确定一个单元格
      const cell_ref = utils.encode_cell(cell); //单元格 A1、A2
      if (wb.Sheets[sheetName][cell_ref]) {
        // if (R == 0){
        if (R < titleNum) {
          wb.Sheets[sheetName][cell_ref].s = {
            //设置第一行单元格的样式 style
            font: {
              bold: true
            },
            alignment: {
              horizontal: 'center',
              vertical: 'center'
            },
            fill: {
              fgColor: { rgb: 'f1f1f1' }
            },
            border: borderStyle //用上面定义好的边框样式
          };
        } else {
          wb.Sheets[sheetName][cell_ref].s = {
            alignment: {
              horizontal: 'left',
              vertical: 'center',
              wrapText: true
            },
            border: borderStyle //用上面定义好的边框样式
          };
        }
        //动态自适应：计算列宽
        const va = JSON.parse(JSON.stringify(wb.Sheets[sheetName][cell_ref].v));
        const card1 = JSON.parse(JSON.stringify(va)).match(/[\u4e00-\u9fa5]/g); //匹配中文
        let card11 = '';
        if (card1) {
          card11 = card1.join('');
        }
        // eslint-disable-next-line no-control-regex
        const card2 = JSON.parse(JSON.stringify(va)).replace(/([^\u0000-\u00FF])/g, ''); //剔除中文
        let st = 0;
        if (card11) {
          // st += card11.length * 16  //中文字节码长度
          st += card11.length * 20; //中文字节码长度
        }
        if (card2) {
          // st += card2.length * 8  //非中文字节码长度
          st += card2.length * 10; //非中文字节码长度
        }
        if (st > len) {
          len = st;
        }
      } else {
        wb.Sheets[sheetName][cell_ref] = wb.Sheets[sheetName][cell_ref] || {};
        wb.Sheets[sheetName][cell_ref].s = {
          //设置第一行单元格的样式 style
          border: borderStyle //用上面定义好的边框样式
        };
      }
    }
    if (len > len_max) {
      //最大宽度
      len = len_max;
    }
    cWidth.push({ wpx: len }); //列宽
  }
  wb.Sheets[sheetName]['!cols'] = cWidth;
  const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };
  const wbout = XLSXStyle.write(wb, wopts); //一定要用XLSXStyle不要用XLSX，XLSX是没有格式的！
  FileSaver(new Blob([s2ab(wbout)], { type: '' }), fileName);
}

function s2ab(s) {
  const buf = new ArrayBuffer(s.length);
  const view = new Uint8Array(buf);
  for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xff;
  return buf;
}
